import React from 'react';
import { Table } from 'antd';

import mixedSort from './mixedSort';
import styles from './index.less';

const generateId = (value = []) => value.join('-');

const PureSalaryRefTable = ({
    cityList = [],
    loading = false,
    salaryData: data = [],
    selectCity,
    positionCode = ''
}) => {
    const [expandKeys, setExpandKeys] = React.useState([]);
    const mapWord = {
        1: 'firstLine',
        2: 'secondLine'
    };

    // 排序规则： 先排一线城市还是二线城市，然后再按a-z中英文混合排序
    const displayData = (() => {
        const result = [];
        if (cityList.length === 0 || data.length === 0) return result;

        // 对指定字段进行一次排序
        const sortArr = ['微微', '美世', '对标公司'];
        const dataList = [];

        const existCity = cityList.find(item => item.dictValue === selectCity?.dictValue);

        sortArr.forEach(item => {
            const arr = data.filter(subItem => subItem.salaryStandardName === item);
            if (arr?.length > 0) {
                dataList.push(...arr);
            }
        });

        // 根据selectCity来排序，涉及一二线以及一二线中的城市排序，越发复杂
        const getSortedList = () => {
            const arr1 = [];
            const arr2 = [];
            if (cityList.length > 0) {
                let sortCityList = mixedSort(cityList, ['dictName']);

                if (existCity) {
                    sortCityList = [
                        existCity,
                        ...mixedSort(
                            cityList.filter(item => item !== existCity),
                            ['dictName']
                        )
                    ];
                }

                sortCityList.forEach(city => {
                    const cityFlag = city.remark;
                    if (cityFlag === '1') {
                        arr1.push(city);
                    } else if (cityFlag === '2') {
                        arr2.push(city);
                    }
                });
            }

            if (existCity) {
                return existCity.remark === '1' ? [...arr1, ...arr2] : [...arr2, ...arr1];
            }

            return [...arr1, ...arr2];
        };

        const sortedList = getSortedList();

        if (sortedList.length > 0) {
            sortedList.forEach(city => {
                dataList.forEach(item => {
                    const cityFlag = city.remark;
                    result.push({
                        ...item,
                        id: generateId([positionCode, city.id, item.id]),
                        cityName: city.dictName,
                        cityId: city.id,
                        cityDictValue: cityFlag,
                        cityLevel: cityFlag === '1' ? '一线城市' : '二线城市',
                        ninety: item[`${mapWord[cityFlag]}NineQuantile`],
                        seventy: item[`${mapWord[cityFlag]}SevenQuantile`],
                        fifty: item[`${mapWord[cityFlag]}FiveQuantile`],
                        twentyFive: item[`${mapWord[cityFlag]}TwoQuantile`]
                    });
                });
            });
        }
        return result;
    })();

    // if (selectCity) {
    //     displayData.sort(a => (a.cityDictValue === selectCity.remark ? -1 : 0));
    // }

    const handleExpandedChange = expandedRows => {
        setExpandKeys(expandedRows);
    };

    const expandStyle = {
        display: 'inline-block',
        fontSize: '16px',
        border: '1px solid #eee',
        height: '17px',
        width: '16px',
        lineHeight: '12px',
        paddingLeft: '2px',
        textAlign: 'center',
        verticalAlign: 'middle'
    };

    const renderFirstTitle = () => {
        const expandIcon =
            displayData && displayData.length > 0 ? (
                <a
                    style={expandStyle}
                    onClick={() => {
                        if (expandKeys.length > 0) {
                            setExpandKeys([]);
                        } else {
                            setExpandKeys(displayData && displayData.map(item => item.id));
                        }
                    }}
                >
                    {expandKeys.length > 0 ? '-' : '+'}
                </a>
            ) : null;
        return (
            <>
                {cityList.length > 1 && expandIcon}
                <span style={{ paddingLeft: 10, marginLeft: cityList.length > 1 ? 0 : '16px' }}>城市</span>
            </>
        );
    };

    const columnWidth = {
        width: 140
    };

    const columns = [
        {
            title: renderFirstTitle(),
            dataIndex: 'cityName',
            key: 'cityName',
            ellipsis: true,
            ...columnWidth
        },
        {
            title: '数据名称',
            dataIndex: 'salaryStandardName',
            key: 'salaryStandardName',
            ellipsis: true,
            ...columnWidth
        },
        {
            title: '参考职位类别',
            dataIndex: 'postTypeName',
            key: 'postTypeName',
            ellipsis: true,
            ...columnWidth
        },
        {
            title: '参考职位',
            dataIndex: 'postName',
            key: 'standardPostName',
            ellipsis: true,
            ...columnWidth
        },
        {
            title: '参考标准',
            dataIndex: 'cityLevel',
            key: 'cityLevel',
            ...columnWidth
        },
        {
            title: '结算货币',
            dataIndex: 'currency',
            key: 'currency',
            ...columnWidth
        },
        {
            title: '25分位',
            dataIndex: 'twentyFive',
            key: 'twentyFive',
            ...columnWidth
        },
        {
            title: '50分位',
            dataIndex: 'fifty',
            key: 'fifty',
            ...columnWidth
        },
        {
            title: '75分位',
            dataIndex: 'seventy',
            key: 'seventy',
            ...columnWidth
        },
        {
            title: '90分位',
            dataIndex: 'ninety',
            key: 'ninety',
            ...columnWidth
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            ellipsis: true,
            ...columnWidth
        }
    ];

    const getDataSource = displayData.map(item => {
        const extra = {};
        if (item.referencePostInfo) {
            const extraJSONObj = JSON.parse(item.referencePostInfo);
            const secondKey = columns[1].dataIndex;
            let extraData = Array.isArray(extraJSONObj) ? [...extraJSONObj] : [extraJSONObj];
            extraData = extraData.map(eItem => ({
                ...eItem,
                id: generateId(['ext', positionCode, item.cityId, eItem.id]),
                cityLevel: item.cityDictValue === '1' ? '一线城市' : '二线城市',
                ninety: eItem[`${mapWord[item.cityDictValue]}NineQuantile`],
                seventy: eItem[`${mapWord[item.cityDictValue]}SevenQuantile`],
                fifty: eItem[`${mapWord[item.cityDictValue]}FiveQuantile`],
                twentyFive: eItem[`${mapWord[item.cityDictValue]}TwoQuantile`]
            }));
            if (extraData.length) {
                extra.children = [
                    {
                        [secondKey]: '参考数据',
                        id: generateId(['ext-title', positionCode, item.cityId, item.id])
                    },
                    ...extraData
                ];
            }
        }
        return {
            ...item,
            ...extra
        };
    });

    React.useEffect(() => {
        if (displayData.length > 0) {
            // 默认展开所有行
            setExpandKeys(displayData.map(item => item.id));
        }
    }, [data]);

    return (
        <Table
            rowKey="id"
            scroll={{ x: 'max-content' }}
            className={styles.dataUpdateTable}
            expandedRowKeys={expandKeys}
            onExpandedRowsChange={handleExpandedChange}
            dataSource={getDataSource}
            columns={columns}
            pagination={false}
            loading={loading}
        />
    );
};
export default React.memo(PureSalaryRefTable);
